package com.yxzr.youyou;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hjq.baselibrary.base.BaseDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yxzr.youyou.base.BaseActivity;
import com.yxzr.youyou.bean.UserInfoBean;
import com.yxzr.youyou.retrofit.BaseObserver;
import com.yxzr.youyou.retrofit.DataUrl;
import com.yxzr.youyou.retrofit.RequestUtil;
import com.yxzr.youyou.utils.NullStringToEmptyAdapterFactory;
import com.yxzr.youyou.utils.SharedPreferencesHelper;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.OptionPicker;
import cn.qqtheme.framework.util.ConvertUtils;
import cn.qqtheme.framework.widget.WheelView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class PeopleDataActivity extends BaseActivity implements View.OnClickListener{
    private ImageView peopledata_img_avatar;
    private TextView peopledata_tv_nickname,peopledata_tv_sex,peopledata_tv_data,peopledata_tv_save;
    private EditText peopledata_et_email,peopledata_et_introduce;
    private RelativeLayout peopledata_rel_avatar;
    private LinearLayout peopledata_linear_sex,peopledata_linear_date;
    private View dialogView;
    private ArrayList<LocalMedia> mReturnList = new ArrayList<>();
    private ArrayList<String> selectList = new ArrayList<>();
    private SharedPreferencesHelper sp;
    private UserInfoBean.DataBean userInfoBean;
    private String sex = "1";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_peopledata);
        sp = new SharedPreferencesHelper(this,"logindata");
        userInfoBean = (UserInfoBean.DataBean) getIntent().getSerializableExtra("userinfo");
        setTitleWithBack();
        initView();
    }

    private void initView() {
        peopledata_tv_nickname = findViewById(R.id.peopledata_tv_nickname);
        peopledata_tv_sex = findViewById(R.id.peopledata_tv_sex);
        peopledata_tv_data = findViewById(R.id.peopledata_tv_data);
        peopledata_tv_save = findViewById(R.id.peopledata_tv_save);
        peopledata_et_email = findViewById(R.id.peopledata_et_email);
        peopledata_et_introduce = findViewById(R.id.peopledata_et_introduce);
        peopledata_img_avatar = findViewById(R.id.peopledata_img_avatar);
        peopledata_rel_avatar = findViewById(R.id.peopledata_rel_avatar);
        peopledata_linear_sex = findViewById(R.id.peopledata_linear_sex);
        peopledata_linear_date = findViewById(R.id.peopledata_linear_date);

        peopledata_rel_avatar.setOnClickListener(this);
        peopledata_linear_date.setOnClickListener(this);
        peopledata_linear_sex.setOnClickListener(this);
        peopledata_tv_save.setOnClickListener(this);

        sex = userInfoBean.getGender();

        Glide.with(PeopleDataActivity.this)
                .setDefaultRequestOptions(
                        new RequestOptions()
                                .frame(1000000)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .centerCrop()
                                .error(R.mipmap.default_avatar)
                                .placeholder(R.mipmap.default_avatar))
                .load(DataUrl.imgUrl+userInfoBean.getHead_pic())
                .apply(RequestOptions.bitmapTransform(new CropCircleTransformation()))
                .into(peopledata_img_avatar);

        peopledata_tv_nickname.setText(userInfoBean.getUsername());
        if ("1".equals(userInfoBean.getGender())){
            peopledata_tv_sex.setText("男");
        }else if("0".equals(userInfoBean.getGender())){
            peopledata_tv_sex.setText("女");
        }else {
            peopledata_tv_sex.setText("保密");
        }

        peopledata_tv_data.setText(userInfoBean.getBirthday());
        peopledata_et_email.setText(userInfoBean.getEmail());
        peopledata_et_introduce.setText(userInfoBean.getIntroduction());
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.peopledata_rel_avatar:
                new BaseDialog.Builder(this)
                        .setContentView(R.layout.avatar_dialog_layout)
                        .setWidth(800)
                        .setOnClickListener(R.id.avatar_linear_photo, new BaseDialog.OnClickListener() {
                            @Override
                            public void onClick(BaseDialog dialog, View view) {
                                //拍照
                                selectList.clear();
                                dialog.dismiss();
                                startPhoto();
                            }
                        })
                        .setOnClickListener(R.id.avatar_linear_picture, new BaseDialog.OnClickListener() {
                            @Override
                            public void onClick(BaseDialog dialog, View view) {
                                //相册
                                selectList.clear();
                                dialog.dismiss();
                                startPicture();
                            }
                        })
                        .show();
                break;
            case R.id.peopledata_linear_sex:
                onOptionPicker();
                break;
            case R.id.peopledata_linear_date:
                onYearMonthDayPicker();
                break;
            case R.id.peopledata_tv_save:
                initData();
                break;
        }
    }
    public void onOptionPicker() {
        OptionPicker picker = new OptionPicker(this, new String[]{
                "女", "男","保密"
        });
        picker.setCanceledOnTouchOutside(false);
        picker.setDividerRatio(WheelView.DividerConfig.FILL);
        picker.setShadowColor(Color.RED, 20);
        picker.setSelectedIndex(Integer.parseInt(sex));
        picker.setCycleDisable(true);
        picker.setTextSize(14);
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                if ("男".equals(item)){
                    sex = "1";
                }else if("女".equals(item)){
                    sex = "0";
                }else {
                    sex = "2";
                }
                peopledata_tv_sex.setText(item);
            }
        });
        picker.show();
    }

    public void onYearMonthDayPicker() {
        final DatePicker picker = new DatePicker(this);
        picker.setCanceledOnTouchOutside(false);
        picker.setUseWeight(true);
        picker.setTopPadding(ConvertUtils.toPx(this, 10));
        picker.setRangeEnd(2050, 12, 31);
        picker.setRangeStart(1970, 1, 1);
        picker.setSelectedItem(2019, 1, 5);
        picker.setResetWhileWheel(false);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                peopledata_tv_data.setText(year+month+day);
            }
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }

    private void initData(){
        if (TextUtils.isEmpty(peopledata_et_email.getText().toString().trim())){
            Toast.makeText(PeopleDataActivity.this,"邮箱不能为空",Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(peopledata_tv_data.getText().toString().trim())){
            Toast.makeText(PeopleDataActivity.this,"请选择生日",Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(peopledata_tv_sex.getText().toString().trim())){
            Toast.makeText(PeopleDataActivity.this,"请选择性别",Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(peopledata_et_introduce.getText().toString().trim())){
            Toast.makeText(PeopleDataActivity.this,"个性签名不能为空",Toast.LENGTH_LONG).show();
            return;
        }
        RequestUtil.getInstence().API().updateData((String) sp.getSharedPreference("token",""),(String) sp.getSharedPreference("userid",""),
                peopledata_et_email.getText().toString().trim(),peopledata_tv_data.getText().toString().trim(),
                sex,peopledata_et_introduce.getText().toString().trim())
                .subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
                .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
                .subscribe(new BaseObserver(this,true){
                    @Override
                    protected void onSuccees(String t) {
                        Toast.makeText(PeopleDataActivity.this,"修改成功",Toast.LENGTH_LONG).show();
                        finish();
                    }

                    @Override
                    protected void onFail(int error_code) {

                    }

                    @Override
                    protected void onComp() {

                    }

                    @Override
                    protected void onErr(Throwable e) {

                    }
                });
    }

    private void startPicture() {
        PictureSelector.create(this)
                .openGallery(PictureConfig.TYPE_IMAGE)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .circleDimmedLayer(false)// 是否圆形裁剪
//                .selectionMedia(mReturnList)// 是否传入已选图片
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    private void startPhoto() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .circleDimmedLayer(false)// 是否圆形裁剪
//                .selectionMedia(mReturnList)// 是否传入已选图片
                .forResult(PictureConfig.REQUEST_CAMERA);//结果回调onActivityResult code
    }

    //上传图片
    private void uploadImage(final String url){
        Map<String, RequestBody> params = new HashMap<>();
        //以下参数是伪代码，参数需要换成自己服务器支持的
        params.put("token", convertToRequestBody((String) sp.getSharedPreference("token","")));//WifiUtils.getConnectedWifiMacAddress(KaoQinActivity.this)
        params.put("id", convertToRequestBody((String) sp.getSharedPreference("userid","")));//WifiUtils.getConnectedWifiMacAddress(KaoQinActivity.this)

        List<File> fileList = new ArrayList<>();
        fileList.add(new File(url));

        List<MultipartBody.Part> partList = filesToMultipartBodyParts(fileList);
        RequestUtil.getInstence().API().updateImage(params,partList)
                .subscribeOn(Schedulers.io()) // 在子线程中进行Http访问
                .observeOn(AndroidSchedulers.mainThread()) // UI线程处理返回接口
                .subscribe(new BaseObserver(this,true) {
                    @Override
                    protected void onSuccees(String t) {
                        Glide.with(PeopleDataActivity.this)
                                .setDefaultRequestOptions(
                                        new RequestOptions()
                                                .frame(1000000)
                                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                                .centerCrop()
                                                .error(R.drawable.message_ms)
                                                .placeholder(R.drawable.message_ms))
                                .load(new File(url))
                                .apply(RequestOptions.bitmapTransform(new CropCircleTransformation()))
                                .into(peopledata_img_avatar);
                        Toast.makeText(PeopleDataActivity.this,"修改成功",Toast.LENGTH_LONG).show();
                    }

                    @Override
                    protected void onFail(int error_code) {

                    }

                    @Override
                    protected void onComp() {

                    }

                    @Override
                    protected void onErr(Throwable e) {

                    }
                });
    }

    private RequestBody convertToRequestBody(String param){
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), param);
        return requestBody;
    }
    private List<MultipartBody.Part> filesToMultipartBodyParts(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        for (File file : files) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST: //相册
                // 图片选择结果回调
                mReturnList = (ArrayList<LocalMedia>) PictureSelector.obtainMultipleResult(data);
                selectList.clear();
                if (mReturnList != null && mReturnList.size() > 0) {
                    for (LocalMedia lm : mReturnList) {
                        String url = "";
                        if (lm.isCompressed()) {
                            url = lm.getCompressPath();
                        } else if (lm.isCut()) {
                            url = lm.getCutPath();
                        } else {
                            url = lm.getPath();
                        }
                        selectList.add(url);
                    }
                }
                if (selectList == null || selectList.size() == 0) {
                    Toast.makeText(this,"选择图片失败",Toast.LENGTH_LONG).show();
                } else {
                    uploadImage(selectList.get(0));
                }
                break;

            case PictureConfig.REQUEST_CAMERA: //相机
                // 图片选择结果回调
                mReturnList = (ArrayList<LocalMedia>) PictureSelector.obtainMultipleResult(data);
                selectList.clear();
                if (mReturnList != null && mReturnList.size() > 0) {
                    for (LocalMedia lm : mReturnList) {
                        String url = "";
                        if (lm.isCompressed()) {
                            url = lm.getCompressPath();
                        } else if (lm.isCut()) {
                            url = lm.getCutPath();
                        } else {
                            url = lm.getPath();
                        }
                        selectList.add(url);
                    }
                }
                if (selectList == null || selectList.size() == 0) {
                    Toast.makeText(this,"选择图片失败",Toast.LENGTH_LONG).show();
                } else {
                    uploadImage(selectList.get(0));
                }
                break;
        }

    }

}
